<?php
/**
 * CreateUser: zlh
 * CreateTime: 2022/1/21 16:26
 * Remark:
 */

namespace App\Http\Middleware;

use App\Consts\RedisConsts\RedisConsts;
use App\Consts\ResponseConsts\ResponseStatusConsts;
use App\Func\RequestFunc;
use App\Func\ResponseFunc;
use App\Func\TokenFuc;
use App\Models\Log\OperationLogModel;
use App\Tools\Log\Log;
use App\Tools\Token\LoginToken;
use Closure;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Facades\Redis;

class LogMiddleware
{

    private function gl($permitPath,$request){
        foreach($permitPath as $value){
            if(strstr($request->path(),$value)){
                return true;
            }
        }
        return false;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // 允许通过的路由
        $permitPath = TokenFuc::getPermitPath();
        if(!$this->gl($permitPath,$request)){
            $staffId = TokenFuc::getCurrentStaffInfo()['staff_id'] ?? 0;
            $input = $request->all(); //操作的内容
            $path = $request->path();  //操作的路由
            $method = $request->method();  //操作的方法
            $ip = $request->ip();  //操作的IP
            $userId = $staffId;//操作人(要自己获取)
            self::writeLog($userId,$input,$path,$method,$ip);
            $requestId = RequestFunc::getHeaderParams("Transfer-Toc");
            //验证当前验证器是否存在
            $isExist = Redis::exists($requestId);
            if($isExist){
                // 如果存在则进行续期
                $lt = new LoginToken();
                Redis::setex($requestId,RedisConsts::REDIS_TOKEN_CONSTS,Redis::get($requestId));
                Redis::setex($lt->setToken($staffId),RedisConsts::REDIS_TOKEN_CONSTS,$staffId);
            }
        }
        return $next($request);
    }

    public  function writeLog($userId,$input,$path,$method,$ip){
        $log = new OperationLogModel();
        $log->setAttribute('user_id', $userId);
        $log->setAttribute('path', $path);
        $log->setAttribute('method', $method);
        $log->setAttribute('ip', $ip);
        $log->setAttribute('input', json_encode($input, JSON_UNESCAPED_UNICODE));
        $log->save();
    }
}